package com.yjd.comm.base.service.impl;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.apache.commons.lang.StringUtils;
import org.apache.log4j.Logger;
import org.springframework.jdbc.core.JdbcTemplate;

import com.yjd.bi.report.model.BiDatabaseInfoModel;
import com.yjd.bi.report.model.BiTableInfoModel;
import com.yjd.bi.report.util.BiUtil;
import com.yjd.comm.base.dao.IBaseDao;
import com.yjd.comm.base.enums.DbWREnums;
import com.yjd.comm.base.model.Model;
import com.yjd.comm.base.model.PagerModel;
import com.yjd.comm.base.service.IBaseService;
import com.yjd.comm.base.service.ICustomPager;
import com.yjd.comm.system.dto.OperParamDto;
import com.yjd.comm.system.model.AdminLogsModel;
import com.yjd.comm.util.FrameUtil;
import com.yjd.comm.util.PagerUtil;
import com.yjd.comm.util.TableTransferUtil;

/**
 * <b>description</b>：业务层基类，此类中所有方法不要加事务（AOP不会代理基类中的方法,若要加事务，请在子类中重写父类的方法） <br>
 * <b>time</b>：2014-10-13上午11:30:38 <br>
 * <b>author</b>： ready likun_557@163.com
 */
public abstract class TopBaseServiceImpl implements IBaseService {

	/**
	 * logger记录系统日志
	 */
	protected Logger logger = Logger.getLogger(getClass());
	

	public abstract IBaseDao getBaseDao();
	
	public long transferFromOri(String schema,String tablename) throws Exception{
	    	this.getBaseDao().excuteSql("truncate "+tablename, true);
	    	long count= this.getBaseDao().getModelListCountOri(FrameUtil.newHashMap(), schema);
	    	return count;
	 }
	
	public long localCount(BiDatabaseInfoModel toDb,BiTableInfoModel toTable) throws Exception{
		Long count= BiUtil
				.getJdbcTemplate(toDb).queryForLong(String.format("select count(1) from %s ", toTable.getTable_name()));
    	return count;
	}
	
	public long transferFromOri(BiDatabaseInfoModel fromDb,BiDatabaseInfoModel toDb,BiTableInfoModel toTable) throws Exception{
		BiUtil
		.getJdbcTemplate(toDb).update("truncate "+toTable.getTable_name());
    	return localCount(fromDb,toTable);
	}
	
	public long transferOne(BiDatabaseInfoModel fromDb,BiTableInfoModel fromTable,
			BiDatabaseInfoModel toDb,BiTableInfoModel toTable,Long index) throws Exception{
			// 业务数据
			if (fromTable == null && logger.isInfoEnabled()) {
				logger.info("数据迁移表不存在!");
				return 0l;
			}
			// 数据抽取中原表和目标表关联信息
			if (toDb != null) {
					// 在业务库查询记录
					List<Map<String, Object>> rows = BiUtil
							.getJdbcTemplate(fromDb)
							.queryForList(
									String.format(
											"select * from %s limit ?,?",
											fromTable.getTable_name(),
											fromTable.getPk_field_name()),
									index,TableTransferUtil.TRANSFER_BATCH);
					// 获取表的列明
					List<String> columnNames = BiUtil.getColumnNames(
							toTable.getTable_name(),
							BiUtil.getJdbcTemplate(toDb));
					int count=0;
					if (rows != null && !rows.isEmpty()) {
						StringBuilder colSql = new StringBuilder();
						StringBuilder colParam = new StringBuilder();
						List<Object> colParamValues = FrameUtil
								.newArrayList();
						for(Map<String,Object> row : rows){
							count++;
							colParam.append("(");
							StringBuilder colParam_temp = new StringBuilder();
							for (String column : columnNames) {
								if(count==1){
								colSql.append("`").append(column)
										.append("`,");
								}
								colParam_temp.append("?").append(",");
								colParamValues.add(row.get(column));
							}
							colParam.append(colParam_temp.substring(0,
									colParam_temp.length() - 1)).append("),");
						}
						final String insertSql = String.format(
								"insert into %s (%s) values %s",
								toTable.getTable_name(), colSql
										.substring(0,
												colSql.length() - 1),
								colParam.substring(0,
										colParam.length() - 1));
						final Object[] insertArgs = colParamValues
								.toArray();
						// 新增和修改：先删除输入，然后执行插入
						BiUtil.execute(toDb,
								new BiUtil.ITransExecute<Boolean>() {
									@Override
									public Boolean execute(
											JdbcTemplate jt)
											throws Exception {
										// 执行插入
										jt.update(insertSql, insertArgs);
										return true;
									}
								});
						
					}
					return rows.size();
				}
			return 0l;
	}
	
	public long transferBatch(String schema,Long t) throws Exception{
		JdbcTemplate jt=BiUtil.getJdbcTemplate(null);
		Map paramMap=FrameUtil.newHashMap();
    	paramMap.put("dbtype","mysql");
		paramMap.put("rowstartindex",t );
		paramMap.put("rowendindex", TableTransferUtil.TRANSFER_BATCH);
    	List list=this.getBaseDao().getModelListOri(paramMap, schema);
		this.getBaseDao().insertBatch(list, true);
		return list.size();
	}

	/**
	 * 根据id获取对象
	 * 
	 * @param id
	 * @return
	 * @throws Exception
	 */
	@SuppressWarnings("unchecked")
	public <T extends Model> T getModelById(Object id, DbWREnums dbwr) throws Exception {
		if (id != null) {
			Map<Object, Object> map = new HashMap<Object, Object>();
			map.put(this.getBaseDao().getPrimaryKeyName(), id);
			List<T> list = this.getBaseDao().getModelList(map, dbwr.isWrite());
			if (list.size() == 0) {
				return null;
			}
			return list.get(0);
		}
		return null;
	}

	/**
	 * 获取符合条件的对象数量
	 */
	@SuppressWarnings({ "rawtypes", "unchecked" })
	@Override
	public Long getModelListCount(Map paramMap, DbWREnums dbwr) throws Exception {
		return this.getBaseDao().getModelListCount(paramMap, dbwr.isWrite());
	}

	/**
	 * 获取符合条件的对象列表
	 */
	@SuppressWarnings({ "rawtypes", "unchecked" })
	@Override
	public List getModelList(Map paramMap, DbWREnums dbwr) throws Exception {
		return this.getBaseDao().getModelList(paramMap, dbwr.isWrite());
	}
	
	@SuppressWarnings({ "rawtypes", "unchecked" })
	@Override
	public List getModelList(Map paramMap, long skip, long size, DbWREnums dbwr)
			throws Exception {
		if (paramMap == null) {
			paramMap = FrameUtil.newHashMap();
		}
		paramMap.put("dbtype", this.getBaseDao().getDbtype());
		paramMap.put("rowstartindex", skip);
		paramMap.put("rowendindex", size);
		return this.getBaseDao().getModelList(paramMap, dbwr.isWrite());
	}

	/**
	 * 获取分页数据
	 * 
	 * @param map
	 * @return
	 * @throws Exception
	 */
	@SuppressWarnings({ "rawtypes" })
	@Override
	public PagerModel getPageModel(Map paramMap, DbWREnums dbwr) throws Exception {
		return this.getPageModel(paramMap, this.getBaseDao(), dbwr);
	}

	@SuppressWarnings({ "rawtypes"})
	public PagerModel getPageModel(Map paramMap, final IBaseDao baseDao, final DbWREnums dbwr) throws Exception {
		return this.getPageModel(paramMap, "getModelList", baseDao, dbwr);
	}
	
	@SuppressWarnings({ "unchecked", "rawtypes" })
	@Override
	public <T extends Model> T getModelOne(Map paramMap, DbWREnums dbwr) throws Exception {
		Object obj = this.getBaseDao().getModelOne(paramMap, dbwr.isWrite());
		return (T) obj;
	}

	/**
	 * 根据idList获取列表
	 * 
	 * @param ids
	 * @return
	 * @throws Exception
	 */
	@SuppressWarnings("rawtypes")
	@Override
	public List getModelsByIds(List idList, DbWREnums dbwr) throws Exception {
		return this.getBaseDao().getModelsByIds(idList, dbwr.isWrite());
	}

	/**
	 * 根据idList获取对象列表的map，key为对象的id，value为对象
	 * 
	 * @param idList
	 * @return
	 * @throws Exception
	 */
	@SuppressWarnings("rawtypes")
	@Override
	public Map getModelMapByIds(List idList, DbWREnums dbwr) throws Exception {
		return this.getBaseDao().getModelMapByIds(idList, dbwr.isWrite());
	}

	/**
	 * 记录管理员操作记录
	 * 
	 * @param operParamDto
	 * @param msg
	 *            操作信息
	 * @param time
	 *            操作时间
	 * @throws Exception
	 */
	public void adminLog(OperParamDto operParamDto, String msg, Long time) throws Exception {
	}

	/**
	 * 记录管理员操作记录
	 * 
	 * @param adminLogsModel
	 * @throws Exception
	 */
	public void adminLog(AdminLogsModel adminLogsModel) throws Exception {
	}

	@SuppressWarnings("rawtypes")
	@Override
	public PagerModel getPageModel(Map map, String sqlMapId, DbWREnums dbwr) throws Exception {
		return this.getPageModel(map, sqlMapId, this.getBaseDao(), dbwr);
	}

	@SuppressWarnings({ "rawtypes", "unchecked" })
	public PagerModel getPageModel(Map paramMap, String sqlMapId, final IBaseDao baseDao, final DbWREnums dbwr)
			throws Exception {
		if (StringUtils.isBlank(sqlMapId)) {
			FrameUtil.throwBaseException1("请问你想干嘛?");
		}

		if (paramMap != null) {
			Object obj = paramMap.get("order");
			if (obj != null && paramMap.get("sort") != null) {
				FrameUtil.throwBaseException1("请问你想干嘛?");
			}
			if (obj != null) {
				String order = obj.toString().trim().toUpperCase();
				if (!order.startsWith("ORDER")) {
					FrameUtil.throwBaseException1("请问你想干嘛?");
				}
			}
		}
		return PagerUtil.getPagerModelOfCustom(new ICustomPager() {

			@Override
			public List getPageList(Map<Object, Object> paramMap, String sqlMapId) throws Exception {
				return baseDao.getModelListOfCustom(paramMap, sqlMapId, dbwr.isWrite());
			}

			@Override
			public long getPageCount(Map<Object, Object> paramMap, String sqlMapId) throws Exception {
				return baseDao.getModelListOfCustomCount(paramMap, sqlMapId+"Count", dbwr.isWrite());
			}
		}, paramMap, sqlMapId, baseDao.getDbtype());
	}

}
